const Service = require('egg').Service;
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');

class RunLighthouse extends Service {
    async run({ curUrl, id }) {
        // --chrome-flags="--no-sandbox --headless --disable-gpu" 为了避免linux运行时连接chrome出现问题
        const cmd = `lighthouse ${curUrl} --locale=zh-CN --chrome-flags="--no-sandbox --headless --disable-gpu" --output-path=./lighthouse/${id}.html`;
        return new Promise((resolve, reject) => {
            exec(cmd, async (error, stdout, stderr) => {
                let contentStr = '';
                if (error) {
                    // 证明是由于lighthouse的querybug导致的报错 通过匹配非标准输出里有没有说在根路径有生成默认的html
                    if (
                        stderr.match(/(?<=egg-lighthouse-h5).*?(?=html)/g) &&
                        stderr.match(/(?<=egg-lighthouse-h5).*?(?=html)/g).length &&
                        curUrl.includes('?')
                    ) {
                        // 直接拿默认生成的path文件
                        const newPath = path.resolve(
                            __dirname,
                            '../../' + stderr.match(/(?<=egg-lighthouse-h5).*?(?=html)/g)[0] + 'html'
                        );
                        // 读取lighthouse文件数据
                        contentStr = await this.ctx.service.runLighthouse.readCrawlerData(newPath);
                        resolve({ status: 200, data: contentStr.data, code: 0 });
                    } else {
                        resolve({ status: 200, data: stderr, code: -1 });
                        return;
                    }
                } else {
                    contentStr = await this.ctx.service.runLighthouse.readCrawlerData(
                        path.resolve(__dirname, '../../lighthouse/' + id + '.html')
                    );
                    resolve({ status: 200, data: contentStr.data, code: 0 });
                }
            });
        });
    }

    async readCrawlerData(filePath) {
        return new Promise((resolve, reject) => {
            let str = '';
            const readStream = fs.createReadStream(filePath);
            readStream.on('data', chunk => {
                str += chunk;
            });
            readStream.on('end', () => {
                resolve({ data: str, type: 0 });
                console.log('准备删除文件');
                fs.unlink(filePath, function(err) {
                    if (err) {
                        reject(err);
                        console.log(err);
                        return;
                    }
                    console.log('文件删除成功');
                });
            });
        });
    }
}

module.exports = RunLighthouse;
